package com.bw.home.vm

import com.bw.common.vm.BaseViewModel
import com.bw.home.intent.VideoViewIntent
import com.bw.home.repo.HomeRepository
import com.bw.home.state.VideoUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class VideoViewModel @Inject constructor(private val repository: HomeRepository) :
    BaseViewModel<VideoViewIntent>() {

    private val _uiSharedFlow = MutableSharedFlow<VideoUiState>()
    val uiSharedFlow: SharedFlow<VideoUiState> = _uiSharedFlow.asSharedFlow()

    override fun dispatchIntent(intent: VideoViewIntent) {
        when (intent) {
            is VideoViewIntent.LoadVideos -> loadVideos()
        }
    }

    private fun loadVideos() {
        mViewModelScope.launch(mDispatcher) {
            _uiSharedFlow.emit(VideoUiState.Loading)
            try {
                // 请求推荐视频列表
                repository.getRecommendSimpleVideoList(1, 10).collect { list ->
                    _uiSharedFlow.emit(VideoUiState.VideoListSuccess(list))
                }
            } catch (e: Exception) {
                _uiSharedFlow.emit(VideoUiState.Error(e.message ?: "加载失败"))
            }
        }
    }
}